package com.aggron.service.impl;

import com.aggron.bean.PageQuery;
import com.aggron.bean.PageResult;
import com.aggron.common.JsonData;
import com.aggron.config.JwtConfig;
import com.aggron.constants.ServiceConstants;
import com.aggron.dao.SysUserMapper;
import com.aggron.entity.SysUser;
import com.aggron.exception.ParamException;
import com.aggron.params.UserParams;
import com.aggron.service.ISysUserService;
import com.aggron.util.BeanValidator;
import com.aggron.util.MD5Util;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import com.aggron.util.StringUtils;
import com.aggron.util.jwt.JwtTokenUtil;

import com.baomidou.mybatisplus.plugins.Page;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuhuan
 * @since 2018-06-02
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtConfig jwtConfig;

    @Override
    public void save(UserParams userParams) {
        BeanValidator.check(userParams);
        if(checkTelphoneExist(userParams.getTelephone(),userParams.getId())){
            throw new ParamException("电话号码已存在");
        }
        if(checkMailExist(userParams.getMail(),userParams.getId())){
            throw new ParamException("邮箱已存在");
        }
        SysUser sysUser=SysUser.builder().username(userParams.getUsername()).mail(userParams.getMail()).telephone(userParams.getTelephone()).deptId(userParams.getDeptId()).status(userParams.getStatus()).remark(userParams.getRemark()).build();
        String password="12345678";
        sysUser.setPassword(MD5Util.encrypt(password));
        sysUser.setOperator("admin");//TODO
        sysUser.setOperateIp("127.0.0.1");//TODO
        sysUser.setOperateTime(new Date());
        //TODO send email
        sysUserMapper.insert(sysUser); 
        
        
    }

    /**
     * 检查邮箱是否已存在
     * @param mail
     * @param id
     * @return
     */
    private boolean checkMailExist(String mail, Integer id) {
        //TODO
        return false;
    }


    /**
     * 检查电话是否已存在
     * @param telephone
     * @param id
     * @return
     */
    private boolean checkTelphoneExist(String telephone, Integer id) {
        //TODO
        return false;
    }

    /**
     * 更新用户
     * @param userParams
     */
    @Override
    public void update(UserParams userParams){
        BeanValidator.check(userParams);
        if(checkTelphoneExist(userParams.getTelephone(),userParams.getId())){
            throw new ParamException("电话号码已存在");
        }
        if(checkMailExist(userParams.getMail(),userParams.getId())){
            throw new ParamException("邮箱已存在");
        }
        SysUser before=sysUserMapper.selectById(userParams.getId());
        Preconditions.checkNotNull(before,"待更新的用户不存在");

        SysUser after=SysUser.builder().id(userParams.getId()).username(userParams.getUsername()).mail(userParams.getMail()).telephone(userParams.getTelephone()).deptId(userParams.getDeptId()).status(userParams.getStatus()).remark(userParams.getRemark()).build();
        after.setOperator("admin");//TODO
        after.setOperateIp("127.0.0.1");//TODO
        after.setOperateTime(new Date());
        sysUserMapper.updateById(after);

    }

    @Override
    public JsonData login(SysUser sysUser) throws Exception{
        sysUser.setPassword(MD5Util.encrypt(sysUser.getPassword()));
        SysUser validUser=sysUserMapper.selectOne(sysUser);
        if(sysUser==null|| StringUtils.isEmpty(sysUser.getUsername())
                ||StringUtils.isEmpty(sysUser.getPassword())){

            return JsonData.fail(ServiceConstants.LOGIN_USER_IS_NULL);
        }else if(validUser==null){
            return JsonData.fail(ServiceConstants.LOGIN_USER_NOT_EXIST);
        }else if(validUser.getStatus()!=ServiceConstants.USER_VALID){
            return JsonData.fail(ServiceConstants.LOGIN_USER_IS_INVAILD);
        }
        String token= jwtTokenUtil.generateToken(validUser.getUsername(),jwtConfig.getMd5Key());
        return JsonData.success(token);
    }

    /**
     * 分页查询user
     * @param pageQuery
     * @param userParams
     * @return
     */
    @Override
    public PageResult<Map<String,Object>> pageUser(PageQuery pageQuery, UserParams userParams) {
        //pageQuery.getCurrent(),pageQuery.getPageSize()
        Page page=new Page(pageQuery.getCurrent(),pageQuery.getPageSize());
        List<Map<String,Object>> userList=sysUserMapper.listUser(page,userParams);
        int count =sysUserMapper.countUser(userParams);

        PageResult<Map<String,Object>> pageResult=new PageResult(userList,count,pageQuery);
        return pageResult;
    }

    /**
     * 逻辑删除
     * @param id
     */
    @Override
    public void deleteLogic(Integer id) {
        SysUser before=sysUserMapper.selectById(id);
        Preconditions.checkNotNull(before,"待删除的用户不存在");
        sysUserMapper.deleteLogic(id);
    }
}
